﻿#ifndef CHATLISTMODEL_H
#define CHATLISTMODEL_H

#include <QAbstractListModel>
#include <QItemDelegate>
#include <QLabel>
#include <QTextLayout>
#include "chatcontent.h"

class ChatListModel : public QAbstractListModel
{
    Q_OBJECT
public:
    explicit ChatListModel(QObject *parent = nullptr);
    int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE;
    Qt::ItemFlags flags(const QModelIndex &index) const Q_DECL_OVERRIDE;

    int appendContent(ChatContent *content, qint64 timestamp = 0);
    ChatContent *getContent(int row) const;
    QPair<int, ChatDirection *> findDirection(const QByteArray &mid) const;
    QPair<int, ChatImage *> findImage(const QString &url) const;
    void downloadRequested(QString url);
    void clearAll();
private slots:
    void downloadFinished(QByteArray buffer,QVariant userData);
    void downloadError(QVariant userData);
    void downloadProgress(qint64 received, qint64 total, QVariant userData);
private:
    qint64 lastTimeStamp;
    QStringList waitingList;
    QList<QSharedPointer<ChatContent>> contents;
};

class ChatListDelegate : public QItemDelegate
{
    Q_OBJECT
public:
    explicit ChatListDelegate(QObject *parent = nullptr);
    // painting
    QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
    // editing
    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
    void destroyEditor(QWidget *editor, const QModelIndex &index) const Q_DECL_OVERRIDE;
    void setEditorData(QWidget *editor, const QModelIndex &index) const Q_DECL_OVERRIDE;
    void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
private:
    ChatContent * getContent(const QModelIndex & index) const;
};
#endif // CHATLISTMODEL_H
